package org.phoenixframework.api.rbac.config.security;

import lombok.AllArgsConstructor;
import org.phoenixframework.api.rbac.service.ISysAuthorityService;
import org.phoenixframework.api.rbac.service.ISysUserService;
import org.phoenixframework.common.entity.SysRole;
import org.phoenixframework.common.entity.SysUser;
import org.phoenixframework.common.security.entity.PhoenixSecurityUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelifeke
 * Email: hautxxxyzjk@163.com
 * DateTime: 2021/5/7 9:23
 * Description:
 */
@AllArgsConstructor
@Component("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private final ISysUserService sysUserService;

    private final ISysAuthorityService sysAuthorityService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.findByUsername(username);
        List<String> authorities = sysAuthorityService.findAuthorityValueByUserId(sysUser.getId());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        authorities.forEach(item -> grantedAuthorities.add(new SimpleGrantedAuthority(item)));
        return new PhoenixSecurityUser(sysUser.getId(), sysUser.getDeptId(), sysUser.getUsername(), sysUser.getPassword(), grantedAuthorities);
    }

}
